package com.ruoyi.api.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.api.domain.DictRegion;
import com.ruoyi.api.mapper.DictRegionMapper;
import com.ruoyi.api.service.IDictRegionService;
import com.ruoyi.api.vo.DictRegionVo;
import com.ruoyi.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author 寻觅
 * @since 2025-05-27
 */
@Service
public class DictRegionServiceImpl extends ServiceImpl<DictRegionMapper, DictRegion> implements IDictRegionService {

    public static final String ADDRESS = "address_data:";

    @Autowired
    DictRegionMapper dictRegionMapper;

    @Autowired
    RedisCache redisCache;

    @Override
    public List<DictRegionVo> getlist() {
//        List<DictRegion> dictRegions = dictRegionMapper.selectList(null);
//
//        // 关键优化：预处理数据，构建父节点到子节点的映射
//        Map<String, List<DictRegion>> parentMap = new HashMap<>();
//        for (DictRegion region : dictRegions) {
//            parentMap.computeIfAbsent(region.getParentCode(), k -> new ArrayList<>()).add(region);
//        }
////        // 构建根节点
//        List<DictRegionVo> rootNodes = buildTreeOptimized(parentMap, "0");
//        redisCache.setCacheList(ADDRESS, rootNodes);


        return redisCache.getCacheList(ADDRESS);
    }

    /**
     * 优化后的递归构建树方法（使用预构建的映射）
     */
    private List<DictRegionVo> buildTreeOptimized(Map<String, List<DictRegion>> parentMap, String parentCode) {
        List<DictRegionVo> children = new ArrayList<>();

        List<DictRegion> childrenRegions = parentMap.getOrDefault(parentCode, Collections.emptyList());

        for (DictRegion region : childrenRegions) {
            DictRegionVo vo = new DictRegionVo();

            vo.setCode(region.getCode());
            vo.setName(region.getName());
            vo.setParentCode(region.getParentCode());
            vo.setLevel(region.getLevel());

            List<DictRegionVo> subChildren = buildTreeOptimized(parentMap, region.getCode());
            vo.setChildren(subChildren);

            children.add(vo);
        }

        return children;
    }

    public static void main(String[] args) {

    }
}
